package com.jucai.pppeiyouclient.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.ProjectGlobalVar;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.base.BaseApplication;
import com.jucai.pppeiyouclient.base.BaseParam;
import com.jucai.pppeiyouclient.base.PermissionListener;
import com.jucai.pppeiyouclient.comm.CommonData;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.CommonUtil;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.TextCheckUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

import static com.jucai.pppeiyouclient.R.id.login_agreement;


public class LoginActivity extends BaseActivity {

    public static Activity activity;

    private static final String TAG = "LoginActivity : ";
    private EditText loginPhone, loginPass;
    private TextView loginForgetPass, loginNext, loginRegister, loginAgreement;
    private CheckBox loginAgree;
    private String isEmpty = "";
    private LocationClient mLocationClient;
    private double latitude = 0;
    private double longitude = 0;
    private String locateCity;
    private String registrationId;


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);

        activity = this;

        loginPhone = (EditText) findViewById(R.id.login_phone);
        loginPass = (EditText) findViewById(R.id.login_pass);
        loginForgetPass = (TextView) findViewById(R.id.login_forget_pass);
        loginNext = (TextView) findViewById(R.id.login_next);
        loginRegister = (TextView) findViewById(R.id.title_register);
        loginAgreement = (TextView) findViewById(login_agreement);
        loginAgree = (CheckBox) findViewById(R.id.login_agree);
    }

    @Override
    protected void initData() {
        mLocationClient = new LocationClient(LoginActivity.this);
        mLocationClient.registerLocationListener(new MyLocationListener());
        skipPermission();

        registrationId = JPushInterface.getRegistrationID(this);

        JPushInterface.setAlias(LoginActivity.this, registrationId, new TagAliasCallback() {
            @Override
            public void gotResult(int arg0, String arg1, Set<String> arg2) {
                Log.e("JP", "setAlias " + arg0);
            }
        });
    }

    @Override
    protected void loadNetData() {

    }

    private void skipPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE}, new PermissionListener() {
                @Override
                public void onGranted() {
                    initLocation();
                }

                @Override
                public void onDenied(List<String> deniedPermissions) {
                    for (String p : deniedPermissions) {
                        Toast.makeText(LoginActivity.this,
                                p + "权限被拒绝，将会导致无法定位，请前往权限管理打开", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            initLocation();
        }
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setLocationNotify(false);
        option.setOpenGps(true);
        option.setAddrType("all");
        mLocationClient.setLocOption(option);
        startLocation();
    }

    private void startLocation() {
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient.start();
        } else if (mLocationClient != null) {
            mLocationClient.start();
        }
    }

    @Override
    protected void setListener() {
        loginRegister.setOnClickListener(this);
        loginNext.setOnClickListener(this);
        loginForgetPass.setOnClickListener(this);
        loginAgreement.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient = null;
        }
    }

    private String judgeEmpty() {

        if (!TextCheckUtils.isMobileNumber(loginPhone.getText().toString())) {
            return "手机号格式不对！";
        }

        if (loginPhone.getText().toString().equals("")) {
            return "手机号不能为空";
        } else if (loginPass.getText().toString().equals("")) {
            return "密码不能为空";
        } else {
            return "";
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_forget_pass:
                startActivity(new Intent(LoginActivity.this, ForgetPassActivity.class));
                break;

            case R.id.login_next:
                CommonUtil.hideSoftInput(loginPass);
                isEmpty = judgeEmpty();
                if (isEmpty.equals("")) {
                    if (loginAgree.isChecked()) {

                        HashMap<String, String> param = new HashMap<>();
                        param.put("service", "Accompany_Login.go");
                        param.put("member_phone", loginPhone.getText().toString());
                        param.put("password", loginPass.getText().toString());
                        param.put("jpush_regid", JPushInterface.getRegistrationID(this));
                        LogUtils.e(TAG + "param = " + param);

                        CommonRequestNetData.getJsonObjectData(LoginActivity.this, param, true, new CommonRequestNetData.JsonObjectCallBack() {
                            @Override
                            public void parseJsonObject(JSONObject jsonObject) {
                                LogUtils.e(TAG + "jsObj = " + jsonObject.toString());
                                try {
                                    String token = jsonObject.getString("token");
                                    String memberId = jsonObject.getString("member_id");
                                    String rongyun_token = jsonObject.getString("rongyun_token");
                                    String member_avatar = jsonObject.getString("member_avatar");

                                    final String rongyun_avatar = jsonObject.getString("rongyun_avatar");
                                    final String rongyun_nickname = jsonObject.getString("rongyun_nickname");
                                    RongIM.connect(rongyun_token, new RongIMClient.ConnectCallback() {
                                        @Override
                                        public void onTokenIncorrect() {
                                            LogUtils.e("onTokenIncorrect");
                                        }

                                        @Override
                                        public void onSuccess(String userId) {
                                            LogUtils.e("onSuccess:" + userId);
                                            LoginUtils.saveRongyun_id(activity,userId);
                                            final UserInfo info = new UserInfo(userId, rongyun_nickname, Uri.parse(rongyun_avatar));
                                            RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

                                                @Override
                                                public UserInfo getUserInfo(String userId) {

                                                    return info;
                                                }

                                            }, true);
                                            RongIM.getInstance().setCurrentUserInfo(info);
                                        }

                                        @Override
                                        public void onError(RongIMClient.ErrorCode errorCode) {
                                            LogUtils.e("onError:" + errorCode.getMessage());
                                        }
                                    });

                                    LogUtils.e(TAG + "token = " + token + " , memberId = " + memberId + ",rongyun_token:" + rongyun_token);
                                    LoginUtils.saveMember_avatar(activity,member_avatar);

                                    CommonData.saveLoginData(LoginActivity.this, memberId, loginPhone.getText().toString(), token, rongyun_token);
                                    ToastUtils.showToast("登录成功");
                                    BaseApplication.getBaseApplication().setJPushAliasAndTag();
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    ActivityCollector.removeActivity(LoginActivity.this);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }finally {
                                    ProjectGlobalVar.isSendLocation = true;
                                }
                            }
                        });
                    } else {
                        ToastUtils.showToastCenter("亲，同意PP优约平台服务协议才能继续登录哦~");
                    }
                } else {
                    ToastUtils.showToastCenter(isEmpty);
                }
                break;

            case R.id.title_register:
                startActivity(new Intent(LoginActivity.this, RegisterFirstStepActivity.class));
                break;

            case R.id.login_agreement:

                BaseParam agreementParam = new BaseParam("Public_UserIndex.getSinglePageUrl");
                agreementParam.put("service", "Public_UserIndex.getSinglePageUrl");
                agreementParam.put("article_type", "agreement");
                agreementParam.put("client", "accompany");

                CommonRequestNetData.getJsonObjectData(LoginActivity.this, agreementParam.getParam(), false, new CommonRequestNetData.JsonObjectCallBack() {
                    @Override
                    public void parseJsonObject(JSONObject jsonObject) {
                        try {
                            String url = jsonObject.getString("URL");
                            Intent intent = new Intent(LoginActivity.this, BrowserActivity.class);
                            intent.putExtra("url", url);
                            startActivity(intent);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;
        }
    }


    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (mLocationClient != null && mLocationClient.isStarted()) {
                mLocationClient.stop();
            }
            latitude = bdLocation.getLatitude();
            longitude = bdLocation.getLongitude();
            locateCity = bdLocation.getCity();
            LogUtils.e(TAG + "定位结束 onReceiveLocation：latitude = " + latitude + ",longitude = " + longitude + ",locateCity = " + locateCity);
            SharedPreferencesUtil.saveStringPreference(LoginActivity.this, "PREFERENCE", "locate_city", locateCity);
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            LogUtils.e(TAG + "定位结束 onConnectHotSpotMessage：" + s + "," + i);
        }
    }

}
